package com.ihunanren.biz.function.service.impl;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;

import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.ihunanren.biz.function.Http;
import com.ihunanren.biz.function.TextMather;
import com.ihunanren.biz.function.domain.IpInfo;
import com.ihunanren.biz.function.service.IWeixinService;

public class IpService implements IWeixinService<IpInfo>{

	private final static String youdao_restful_api = "http://www.youdao.com/smartresult-xml/search.s";

	private static final String IPADDRESS_PATTERN = "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
			+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
			+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
			+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])";
	

	private IpInfo convertXml(InputStream inputStream) {
		IpInfo bean = new IpInfo();
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.parse(inputStream);

			bean.setIp(document.getElementsByTagName("ip").item(0).getTextContent());
			bean.setLocation(document.getElementsByTagName("location").item(0).getTextContent());
		} catch (NullPointerException e) {
			throw new IllegalArgumentException("ip is wrong.");
		} catch (Exception e) {
			Throwables.propagate(e);
		}
		return bean;
	}

	@Override
	public List<IpInfo> getResponse(String input) {
		checkArgument(!isNullOrEmpty(input));

		String ip = TextMather.getMatherString(input, IPADDRESS_PATTERN);

		if (isNullOrEmpty(ip)) {
			return null;
		}
		Http http = new Http();
		Map<String, String> m = Maps.newHashMap();
		m.put("type", "ip");
		m.put("q", ip);
		InputStream inputStream = http.doGetAsInputStream(youdao_restful_api, m);
		return Arrays.asList(convertXml(inputStream));
	}

}
